﻿using System;
using System.Data;
using System.Collections.Generic;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

namespace SchoolDB.Util
{
    /// <summary>
    /// 操作JSON函数
    /// </summary>
    public class JsonHelper
    {
        private JObject jObj;
        /// <summary>
        /// 此构造函数应用于获取一层参数列表时,初始化JObject对象
        /// </summary>
        /// <param name="json">json字串(只能含一层),应用于纯参数的情形</param>
        public JsonHelper(string jsonText)
        {
            jObj = JObject.Parse(jsonText);
        }

        /// <summary>
        /// 获得对象经Json序列化后的字符串(日期按JavaScript日期编码)
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="o">需要序列化的对象</param>
        /// <returns>JSON字符串</returns>
        public static string Serialize(Object o)
        {
            try
            {
                return JsonConvert.SerializeObject(o, new JavaScriptDateTimeConverter());
            }
            catch (Exception e)
            {
                //Log
                //e.Message;
                return string.Empty;
                JsonSerializer js = new JsonSerializer();
                
            }
        }

        /// <summary>
        /// 将Json字串反序列化为对象(日期按JavaScript日期反编码)
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="json">json字串</param>
        /// <returns>对象</returns>
        public static T Deserialize<T>(string json)
        {
            T o = JsonConvert.DeserializeObject<T>(json, new JavaScriptDateTimeConverter());
            
            return o;
        }

        /// <summary>
        /// 获得参数名
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetParam(string key)
        {
            if (jObj == null)
            {
                //throw new NotInitException();
                return null;
            }
            else
            {
                return jObj[key].ToString();
            }
        }
    }
}